package com.ansion.utils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.ansion.basetool.preconditions.Preconditions;

import java.util.Collection;

/**
 * created by zhaoyuntao
 * on 24/01/2024
 */
public final class DynamicStringBuilder {
    private final StringBuilder stringBuilder;

    public DynamicStringBuilder() {
        stringBuilder = new StringBuilder();
    }

    public DynamicStringBuilder(int capacity) {
        stringBuilder = new StringBuilder(capacity);
    }

    public DynamicStringBuilder(CharSequence charSequence) {
        stringBuilder = new StringBuilder(charSequence);
    }

    public DynamicStringBuilder append(Object o) {
        Preconditions.checkNotNull(o);
        return appendIf(true, o.toString());
    }

    public DynamicStringBuilder appendIf(boolean ifCondition, String content) {
        if (ifCondition) {
            stringBuilder.append(content);
        }
        return this;
    }

    public DynamicStringBuilder appendIf(boolean ifCondition, @NonNull Appender appender) {
        if (ifCondition) {
            appender.onAppend();
        }
        return this;
    }

    public <T> DynamicStringBuilder append(@Nullable Collection<T> collection, ValueSafeTransfer.ElementIterator2<T> iterator) {
        if (collection != null) {
            int i = 0;
            for (T t : collection) {
                iterator.element(i++, t);
            }
        }
        return this;
    }

    public int length() {
        return stringBuilder.length();
    }

    @NonNull
    @Override
    public String toString() {
        return stringBuilder.toString();
    }

    public interface Appender {

        void onAppend();
    }
}
